package avicit.bdp.dds.api.utils.exportprocess;

import avicit.bdp.common.service.dao.DataSourceDao;
import avicit.bdp.common.service.dto.DataSourceDTO;
import avicit.bdp.dds.dispatch.enums.TaskType;
import avicit.bdp.core.util.json.JSONUtils;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * task node add datasource param strategy
 */
@Service
public class DataSourceParam implements ProcessAddTaskParam, InitializingBean {

    @Autowired
    private DataSourceDao dataSourceMapper;

    /**
     * add datasource params
     * @param taskNode task node json object
     * @return task node json object
     */
    @Override
    public JSONObject addExportSpecialParam(JSONObject taskNode) {
        // add sqlParameters
        JSONObject sqlParameters = JSONUtils.parseObject(taskNode.getString("params"));
        DataSourceDTO dataSource = dataSourceMapper.selectByPrimaryKey((Integer) sqlParameters.get("datasource"));
        if (null != dataSource) {
            sqlParameters.put("datasourceName", dataSource.getDatasourceName());
        }
        taskNode.put("params", sqlParameters);

        return taskNode;
    }

    /**
     * import process add datasource params
     * @param taskNode task node json object
     * @return task node json object
     */
    @Override
    public JSONObject addImportSpecialParam(JSONObject taskNode) {
        JSONObject sqlParameters = JSONUtils.parseObject(taskNode.getString("params"));
        List<DataSourceDTO> dataSources = dataSourceMapper.queryDataSourceByName(sqlParameters.getString("datasourceName"));
        if (CollectionUtils.isNotEmpty(dataSources)) {
            DataSourceDTO dataSource = dataSources.get(0);
            sqlParameters.put("datasource", dataSource.getId());
        }
        taskNode.put("params", sqlParameters);
        return taskNode;
    }


    /**
     * put datasource strategy
     */
    @Override
    public void afterPropertiesSet() {
        TaskNodeParamFactory.register(TaskType.SQL.name(), this);
        TaskNodeParamFactory.register(TaskType.PROCEDURE.name(), this);
    }
}
